import axios from "axios";
import qs from "qs";
import { ElMessage } from "element-plus";

const http = axios.create({
    baseURL: process.env.VUE_APP_API_URL,
    timeout: 5000,
    headers: {
        Accept: "application/json",
        "Content-Type": "application/x-www-form-urlencoded"
    }
})

//请求拦截器
http.interceptors.request.use(
    (config) => {
        // console.log("请求拦截器 config"，config);
        return config;
    },
    (error) => {
        console.log("请求拦截器 error", error);
        return Promise.reject(error);
    }
);

//响应拦截器
http.interceptors.response.use(
    (response) => {
        console.log("响应拦截器 response", response);
        if (response.status !== 200) {
            ElMessage.error("网络错误");
            return false;
        }
        return response.data;
    },
    (error) => {
        console.log("响应拦截器 error", error);
        return Promise.reject(error);
    }
)

const apiRequest = (url: any, param: any, method: any) => {
    param = qs.stringify(param);
    return method === "post" ? http.post(url, param) : method === "get" ? http.get(url, param) : "错误的请求方法";
}

export default apiRequest;
